﻿/*
COPYRIGHT (C) 2011-2013 Raynald Messié

THIS FILE IS PART OF SCRUMPILOT.

SCRUMPILOT IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF 
THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

SCRUMPILOT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT
EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER
GENERAL PUBLIC LICENSE FOR MORE DETAILS.

YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH SCRUMPILOT. 
IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/

using System;
using System.Web.Mvc;
using ScrumPilot.Domain.BPL;
using ScrumPilot.Domain.Models;
using ScrumPilot.Helpers;
using ScrumPilot.TFSHelpers;

namespace ScrumPilot.Controllers
{
    [Authorize]
    public class ConfigController : BaseController
    {
        private ConfigServices _cfm;
        protected ConfigServices ConfModel { get { return _cfm ?? (_cfm = new ConfigServices()); } }

        private ProjectServices _projectServices;
        protected ProjectServices ProjectServices { get { return _projectServices ?? (_projectServices = new ProjectServices(this.TFS)); } }

        [HttpGet]
        public ActionResult InitialConfig()
        {
            return View("Params", new Main
                                      {
                                          TFSUrl = "127.0.0.1",
                                          TFSPort = "8080",
                                          TFSSubDir = "tfs",
                                          ScrumPilotWSAdress = "http://127.0.0.1/WS-TFS/WCFForTFS.svc"
                                      }
                );
        }

        [HttpPost]
        public ActionResult InitialConfig(Main model)
        {
            if (ModelState.IsValid)
            {
                var tfs = new TFSServices(SPHelpers.FormatTFSServerUrl(model.TFSUrl, model.TFSPort, model.TFSSubDir),
                                    model.TFSID, model.TFSPWD);

                if (tfs.Authenticate())
                {
                    if (ConfModel.SaveConfig(model))
                        return RedirectToAction("Index", "Home");
                }
            }
            // ReSharper disable Mvc.ViewNotResolved
            return View();
            // ReSharper restore Mvc.ViewNotResolved
        }

        [HttpGet]
        public ActionResult Projects()
        {
            return View(ProjectServices.GetAllProjects());
        }

        [HttpGet]
        public ActionResult Project(Int32 id)
        {
            return (View(ProjectServices.GetProject(id)));
        }

        [HttpGet]
        public JsonResult ProjectKeys(Int32 id)
        {
            return Json(new Object[] { (new ScrumDashBoardServices(this.TFS)).GetKeyPointProject(id) }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public PartialViewResult ProjectIndicator()
        {
            return PartialView();
        }

        [HttpPost]
        public ActionResult Project(Project model)
        {
            if (ModelState.IsValid)
            {
                // PostBack from submit
                if (ProjectServices.UpdateProject(model))
                {
                    // to do : infor user it is not ok
                    if (this.CurrentUserDB.isadmin)
                    {
                        // Subscribe treatment
                        ProjectServices.SubscribeEvents(model.ID, model.SubscribeCheckin, model.SubscribeWIChanged);
                    }
                    //System.Threading.Tasks.Task.Factory.StartNew(() =>
                    //      {
                    //          var idts = this.TFS.GetTfsUsersInProject(model.Name);
                    //          idts.ForEach(idt => this.TFS.CheckIdentity(idt.Sid, false));
                    //      });
                }
            }
            return View(ProjectServices.GetProject(model.ID));
        }

        [HttpGet]
        public ActionResult Params()
        {
            return View(ConfModel.GetConfig());
        }

        [HttpPost]
        public ActionResult Params(Main model)
        {
            if (ModelState.IsValid)
                ConfModel.SaveConfig(model);
            return View(ConfModel.GetConfig());
        }

        [HttpGet, NoCache]
        public JsonResult LastPrjActivities(int id)
        {
            return Json((new WallServices(this.TFS)).GetProjectWallInfo(0, 30, id, this.CurrentUser, this.CurrentCulture, this.TfsRootUrl), JsonRequestBehavior.AllowGet);
        }

        public override ActionResult YammerAuthorization()
        {
            this.TempData["YammerComeFrom"] = "config";
            return base.YammerAuthorization();
        }

        public ActionResult YammerAuthorizedCode(String code)
        {
            // Back from Yammer OAUth2 with Authorization Code
            if (!String.IsNullOrWhiteSpace(code))
            {
                var yammerService = new YammerServices();
                switch ((string)this.TempData["YammerComeFrom"])
                {
                    case "user": // authorized from user screen
                        yammerService.SaveToken(this.CurrentUserDB.userid, code);
                        return RedirectToAction("UserView", "User", new { id = this.CurrentUserDB.userid });
                    case "config": // authorized from config (ScrumPilot actor)
                        yammerService.SaveYammerAdminToken(code);
                        return RedirectToAction("Params", "Config");
                }
            }
            return null;
        }

        public  RedirectToRouteResult YammerRenewToken()
        {
            var yammerService = new YammerServices();
            yammerService.SaveYammerAdminToken(null);
            return RedirectToAction("Params", "Config");
        }

        
    }
}